﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Windows.Media.Effects;
using System.Windows.Media.Animation;
using System.Threading;
using PRScreenWithKinect.Model;

namespace PRScreenWithKinect
{
	/// <summary>
	/// Interaction logic for GuestBook.xaml
	/// </summary>
	public partial class GuestBook : UserControl,UserControlInterfaceForGesture
	{

        private ArrayList controllerElement;
        private ArrayList guestBooks;
        private UIElement hitElement = null;
        private UIElement hittedElement = null;
        private SolidColorBrush focusColor = Brushes.Orange, defaultColor = Brushes.White;
        private int pageIndex = 0;
        private int mainController;
      //  private int numberPerGroup = 20;
        private int numberPerPage =5;
        private Storyboard bgFX;
        private bool firstTime = true;
        private List<GuestBookModel> guestbooks;
        private System.Timers.Timer updateLastestTime ;
        private QueryDB _query;
        private int showCount = 0 ;
        private string time_lastest_write = "";

		public GuestBook()
		{
			this.InitializeComponent();
            controllerElement = new ArrayList();
            controllerElement.Add(_closeDetail);
            controllerElement.Add(_qrcode);
            mainController = controllerElement.Count; 

            /// Prepare Array Guest Book;  
            guestBooks = new ArrayList();

            /// Get bouce FX from Resouce ; 
            /// 
            bgFX = (Storyboard)this.Resources["bgGroundFX"];

            Storyboard.SetTargetProperty(bgFX.Children[0], new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)"));
            Storyboard.SetTargetProperty(bgFX.Children[1], new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)"));

            /// Create DataFactoy
            DataFactory datafactory = DataFactory.Instance;
            guestbooks = datafactory.getGuestbookModel();

            /// Create QueryDB for little query 

            _query = new QueryDB();

            /// Hide Show Content
            showDetail.Visibility = Visibility.Hidden;

            /// Set Data to Balloon
            /// 
            for (int i = 0; i < numberPerPage; i++)
            {
                setData(i,true);
            }

            setLastestWrite();
            updateLastestTime = new System.Timers.Timer(10*1000);
            updateLastestTime.Elapsed += new System.Timers.ElapsedEventHandler(updateLastestTime_Elapsed);
            updateLastestTime.Start();

            startBalloonAnimation();
         
           
            
		}

        
        void setQRCode(string key)
        {
            //int cid = GlobalConfig.CLIENT_ID;

            //string word = GlobalConfig.SERVER_IP+"admin/guestbook?cid="+cid+"&key="+key;
            //string word_encode = System.Web.HttpUtility.UrlEncode(word);
            //string url_qr_gen = "http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl="+word_encode+"&chld=H|0";
            

            //_qrcode.Source = new BitmapImage(new Uri(url_qr_gen));
        }

        void updateLastestTime_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
        //    Console.WriteLine("Update Lastest");
           LastGuestbook.Dispatcher.Invoke(new Action(delegate()
                {
                    setLastestWrite();
                }));
        
        }



        private void setLastestWrite()
        {
            GuestBookModel g = _query.getLastGuestBook();
            _lHeader.Text = "Lastest by " + g.name + " on " + g.dateTime;
            _lText.Text = g.content;
           
            if(g.imagePath.Equals("")){
                BitmapImage b = new BitmapImage(new Uri(GlobalConfig.SERVER_IP+GlobalConfig.AVATAR_PATH));
                _lImage.Source = b;
            }else{
                BitmapImage b = new BitmapImage(new Uri(g.imagePath));
                _lImage.Source = b;
            }
            if (!g.dateTime.Equals(time_lastest_write))
            {
                time_lastest_write = g.dateTime.ToString();

                // Set Qr code for Guestbook Write 
                string key = _query.getQRKey();
                setQRCode(key);
            }
           

        }
        public void finishHold()
        {
           
             if (hitElement.GetType() == typeof(DataGrid))
            {
                GuestBookModel m = (GuestBookModel)((DataGrid)hitElement).DataContext;
                zoomContent(guestBooks.IndexOf(m));
            }else if(hitElement.Equals(_closeDetail))
             {
                 closeZoom();
             }
             else if (hitElement == _qrcode)
             {
                 string key = _query.updateAndGetQRKey();
                 setQRCode(key);
                 hitElement = null;
             }
           
            //   Console.WriteLine("Type Hit Element : " + hitElement.GetType());
            hittedElement = hitElement;
            hitElement = null;
       
        }



        public void swipeLeft()
        {
            doSwipe(Swipe.Left);
            
        }

        public void swipeRight()
        {
            doSwipe(Swipe.Right);
          
        }

        public void doSwipe(Swipe s)
        {
          //  Boolean check = false;
            if (s == Swipe.Left && pageIndex<1)
            {
                
                    pageIndex++;
                
            }
            else if(s == Swipe.Right && pageIndex>0)
            {
                if (pageIndex > 0)
                {
                    pageIndex--;
                }
              
            }

            if (pageIndex == 0)
            {
                startBalloonAnimation();
            }
            else
            {
                stopBalloonAnimation();
            }

            PaperScroll.ScrollToPosition(548 * pageIndex, 0);
          
         
        }

        private void startBalloonAnimation()
        {
            if (firstTime)
            {
                bgFX.Begin();
                firstTime = !firstTime;
            }
            else
            {
                bgFX.Resume();

            }

            howToWritePanel.Visibility = Visibility.Hidden;
            LastGuestbook.Visibility = Visibility.Hidden;
            _qrcode.Visibility = Visibility.Hidden;
        }
        private void stopBalloonAnimation()
        {
            howToWritePanel.Visibility = Visibility.Visible;
            LastGuestbook.Visibility = Visibility.Visible;
            _qrcode.Visibility = Visibility.Visible;

            bgFX.Pause();
        }

        public void zoomContent(int i)
        {
            GuestBookModel g = (GuestBookModel)guestBooks[i];
            showDetail.Visibility = Visibility.Visible;
            _content.Text = "            "+ g.content;
            _time.Text = g.dateTime.ToLongDateString();
            _name.Text = g.name;

            // Set Image Avatar 
            if (g.imagePath.Equals(""))
            {
                BitmapImage b = new BitmapImage(new Uri(GlobalConfig.SERVER_IP+GlobalConfig.AVATAR_PATH));
                _image.Source = b;
            }
            else
            {
             //   Console.WriteLine("Image Path : "+g.imagePath); 
                BitmapImage b = new BitmapImage(new Uri(g.imagePath));
                _image.Source = b;
            }
         
       
        }

        public void closeZoom()
        {
            showDetail.Visibility = Visibility.Hidden;

        }
   
        public void setData(int i,bool isCreate)
        {
            System.Random RandNum = new System.Random(DateTime.Now.Millisecond+i);
            int numOfData = guestbooks.Count;
            double widthPerWord = 548/numberPerPage;

            GuestBookModel g = guestbooks[0];

            g.balloonPath = "/PRScreenWithKinect;component/Images/Balloon/balloon" + RandNum.Next(1, 4) + ".png";
            guestBooks.Add(g);

            double scaleRatio = 0.1;
            DataGrid dg; 
            if (isCreate)
            {
                dg = new DataGrid();
                dg.Template = (ControlTemplate)this.Resources["MyDataTemplate"];
                TransformGroup tg = new TransformGroup();
                tg.Children.Add(new TranslateTransform());
                tg.Children.Add(new RotateTransform());
                tg.Children.Add(new ScaleTransform(scaleRatio,scaleRatio,0,0));
                
                dg.RenderTransform = tg;
                Paper.Children.Add(dg);
                controllerElement.Add(dg);
            }
            else
            {
                dg = (DataGrid)Paper.Children[i];
            }

            double y = RandNum.Next(600,700);
           int total_time_animate = (int)RandNum.Next(40,50);
            //int total_time_animate = 30;
            dg.DataContext = g;

            int topMargin = 50;
            Canvas.SetLeft(dg, widthPerWord * i+50);
            Canvas.SetTop(dg,topMargin);
         
            guestbooks.Remove(g);
            guestbooks.Add(g);

            Storyboard st = new Storyboard();
            DoubleAnimation translateDB = new DoubleAnimation(topMargin,y, TimeSpan.FromSeconds(total_time_animate));
            DoubleAnimation rotateDB = new DoubleAnimation((RandNum.Next(-10,-1) % 10), (RandNum.Next(2, 10) % 10), TimeSpan.FromSeconds(total_time_animate*0.2));
            DoubleAnimationUsingKeyFrames scaleDBX = new DoubleAnimationUsingKeyFrames();
            scaleDBX.Duration = TimeSpan.FromSeconds(total_time_animate);
 
            scaleDBX.KeyFrames.Add(
               new LinearDoubleKeyFrame(
                  1,// Target value (KeyValue)
                   KeyTime.FromTimeSpan(TimeSpan.FromSeconds(total_time_animate*0.2))) // KeyTime
               );
            scaleDBX.KeyFrames.Add(
                new LinearDoubleKeyFrame(
                   scaleRatio ,// Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(total_time_animate ))) // KeyTime
                );

            DoubleAnimationUsingKeyFrames scaleDBY = new DoubleAnimationUsingKeyFrames();
            scaleDBY.Duration = TimeSpan.FromSeconds(total_time_animate);

            scaleDBY.KeyFrames.Add(
               new LinearDoubleKeyFrame(
                  1,// Target value (KeyValue)
                   KeyTime.FromTimeSpan(TimeSpan.FromSeconds(total_time_animate*0.2))) // KeyTime
               );
            scaleDBY.KeyFrames.Add(
                new LinearDoubleKeyFrame(
                   scaleRatio,// Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(total_time_animate))) // KeyTime
                );



            rotateDB.RepeatBehavior = RepeatBehavior.Forever;
            rotateDB.AutoReverse = true;
            st.Completed += new EventHandler(st_Completed);
           st.Duration = TimeSpan.FromSeconds(total_time_animate);
           st.AccelerationRatio = 0.5;
            st.Children.Add(translateDB);
            st.Children.Add(rotateDB);
            st.Children.Add(scaleDBX);
            st.Children.Add(scaleDBY);


            Storyboard.SetTarget(translateDB,dg);
            Storyboard.SetTarget(rotateDB, dg);
            Storyboard.SetTarget(scaleDBX, dg);
            Storyboard.SetTarget(scaleDBY, dg);

            Storyboard.SetTargetProperty(translateDB, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.Y)"));
            Storyboard.SetTargetProperty(rotateDB, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[1].(RotateTransform.Angle)"));
            Storyboard.SetTargetProperty(scaleDBX, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[2].(ScaleTransform.ScaleX)"));
            Storyboard.SetTargetProperty(scaleDBY, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[2].(ScaleTransform.ScaleY)"));
            st.Begin();
          //  translateDB.Completed += new EventHandler(st_Completed);
            showCount++;
            if (showCount == guestbooks.Capacity)
            {
                showCount = 0;
                guestbooks = DataFactory.Instance.getGuestbookModel();
            }
          
        }


        int tempIndex = 0;
        void st_Completed(object sender, EventArgs e)
        {
            
            Storyboard st = (Storyboard)((ClockGroup)sender).Timeline;
       
             DoubleAnimation db = (DoubleAnimation) st.Children[0];
          //  DoubleAnimation db = (DoubleAnimation)sender;
           // DataGrid dg = (DataGrid)Paper.Children[tempIndex];
             DataGrid dg = (DataGrid)Storyboard.GetTarget(db);

            int i = Paper.Children.IndexOf(dg);
            Paper.Children.Remove(dg);
            setData(tempIndex, true);

            tempIndex = (tempIndex+1)%numberPerPage; 
       //     Console.WriteLine("============= Story Complete ===============");
            
        }



        public bool hitTest(Point p, Window w)
        {
            Boolean isHit = false;

            foreach (UIElement c in controllerElement)
            {
                try
                {
                    Point RhandRelativePoint = c.TransformToAncestor(w).Transform(new Point(0, 0));
                    Point delta = new Point(p.X - RhandRelativePoint.X, p.Y - RhandRelativePoint.Y);
                    if (VisualTreeHelper.HitTest(c, delta) != null)
                    {
                        if (c.Equals(hitElement) && !c.Equals(hittedElement))
                        {
                            if(hitElement == _qrcode && _qrcode.IsVisible){
                                return true;
                            }else if (c.GetType() == typeof(DataGrid) && showDetail.Visibility == Visibility.Hidden)
                            {
                                return true;
                            }
                            else if (c.Equals(_closeDetail) && showDetail.Visibility == Visibility.Visible)
                            {
                                return true;
                            }
                        }
                        else
                        {
                            hitElement = c;
                            return false;

                        }
                    }
                }
                catch
                {
                    controllerElement.Remove(c);
                    break;
                }
               
              
            }




            return isHit;
        }
    }
}